package com.cy.ppj.service.order.impl;

import com.cy.ppj.comm.constant.Constants;
import com.cy.ppj.comm.utils.CommonUtils;
import com.cy.ppj.dao.mapper.manager.ManagerMapper;
import com.cy.ppj.dao.mapper.order.OrderGoodsExtraInfoMapper;
import com.cy.ppj.dao.mapper.order.OrderImageMapper;
import com.cy.ppj.dao.mapper.order.OrderManagerMapper;
import com.cy.ppj.model.PageBean;
import com.cy.ppj.model.ao.order.MallOrderAuditPurchaseProofAO;
import com.cy.ppj.model.domian.admin.Manager;
import com.cy.ppj.model.domian.order.OrderGoodsExtraInfo;
import com.cy.ppj.model.domian.order.OrderManager;
import com.cy.ppj.model.enums.order.GoodsOrderStatus;
import com.cy.ppj.model.enums.order.OrderFinalStatusE;
import com.cy.ppj.model.enums.order.OrderImageType;
import com.cy.ppj.model.query.order.MallOrderListAdminQuery;
import com.cy.ppj.model.vo.order.MallOrderDetailAdminVO;
import com.cy.ppj.model.vo.order.MallOrderListAdminVO;
import com.cy.ppj.model.vo.order.OrderImageListVO;
import com.cy.ppj.service.BaseService;
import com.cy.ppj.service.comm.FileService;
import com.cy.ppj.service.dict.DictService;
import com.cy.ppj.service.order.MallOrderService;
import com.cy.ppj.service.order.MallOrderStatusService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description 马先生商城 分期订单 service
 * @Author tanyilin
 * @Date 2019/4/3 11:49
 */
@Slf4j
@Service
public class MallOrderServiceImpl extends BaseService implements MallOrderService {

    @Autowired
    private OrderGoodsExtraInfoMapper orderGoodsExtraInfoMapper;
    @Autowired
    private OrderImageMapper          orderImageMapper;
    @Autowired
    private FileService               fileService;
    @Autowired
    private MallOrderStatusService    mallOrderStatusService;
    @Autowired
    private ManagerMapper             managerMapper;
    @Autowired
    private OrderManagerMapper        orderManagerMapper;
    @Autowired
    private DictService               dictService;

    @Override
    public PageBean<MallOrderListAdminVO> selectApplyingMallOrderList(MallOrderListAdminQuery query) {

        //家具分期订单ID列表
        List<Long> productIdsList = dictService.selectProductIdsListInCache();
        productIdsList = productIdsList.stream().filter(id -> !Constants.JYD_PRODUCTID.equals(id)).collect(Collectors.toList());
        query.setProductIdsList(productIdsList);

        int total = orderGoodsExtraInfoMapper.selectApplyingMallOrderListCount(query);
        List<MallOrderListAdminVO> list = new ArrayList<>();
        if(total > 0) {
            query.startPage();
            list = orderGoodsExtraInfoMapper.selectApplyingMallOrderList(query);
        }
        return new PageBean<>(list, total);
    }

    @Override
    public PageBean<MallOrderListAdminVO> selectDecisionPassMallOrderList(MallOrderListAdminQuery query) {

        //家具分期订单ID列表
        List<Long> productIdsList = dictService.selectProductIdsListInCache();
        productIdsList = productIdsList.stream().filter(id -> !Constants.JYD_PRODUCTID.equals(id)).collect(Collectors.toList());
        query.setProductIdsList(productIdsList);

        int total = orderGoodsExtraInfoMapper.selectDecisionPassMallOrderListCount(query);
        List<MallOrderListAdminVO> list = new ArrayList<>();
        if(total > 0) {
            query.startPage();
            list = orderGoodsExtraInfoMapper.selectDecisionPassMallOrderList(query);
            list.stream().forEach(o -> {
                if(!CommonUtils.isEmpty(o.getYearRate())) {
                    o.setYearRateBd(new BigDecimal(o.getYearRate()).multiply(new BigDecimal(100)));
                    o.setYearRate(null);
                }
            });
        }
        return new PageBean<>(list, total);
    }

    @Override
    public PageBean<MallOrderListAdminVO> selectUnassignedMallOrderList(MallOrderListAdminQuery query) {

        //家具分期订单ID列表
        List<Long> productIdsList = dictService.selectProductIdsListInCache();
        productIdsList = productIdsList.stream().filter(id -> !Constants.JYD_PRODUCTID.equals(id)).collect(Collectors.toList());
        query.setProductIdsList(productIdsList);

        int total = orderGoodsExtraInfoMapper.selectUnassignedMallOrderListCount(query);
        List<MallOrderListAdminVO> list = new ArrayList<>();
        if(total > 0) {
            query.startPage();
            list = orderGoodsExtraInfoMapper.selectUnassignedMallOrderList(query);
            list.stream().forEach(o -> {
                if(!CommonUtils.isEmpty(o.getYearRate())) {
                    o.setYearRateBd(new BigDecimal(o.getYearRate()).multiply(new BigDecimal(100)));
                    o.setYearRate(null);
                }
            });
        }
        return new PageBean<>(list, total);
    }

    @Override
    public PageBean<MallOrderListAdminVO> selectAuditingMallOrderList(MallOrderListAdminQuery query) {

        //家具分期订单ID列表
        List<Long> productIdsList = dictService.selectProductIdsListInCache();
        productIdsList = productIdsList.stream().filter(id -> !Constants.JYD_PRODUCTID.equals(id)).collect(Collectors.toList());
        query.setProductIdsList(productIdsList);

        int total = orderGoodsExtraInfoMapper.selectAuditingMallOrderListCount(query);
        List<MallOrderListAdminVO> list = new ArrayList<>();
        if(total > 0) {
            query.startPage();
            list = orderGoodsExtraInfoMapper.selectAuditingMallOrderList(query);
            list.stream().forEach(o -> {
                if(!CommonUtils.isEmpty(o.getYearRate())) {
                    o.setYearRateBd(new BigDecimal(o.getYearRate()).multiply(new BigDecimal(100)));
                    o.setYearRate(null);
                }
            });
        }
        return new PageBean<>(list, total);
    }

    @Override
    public PageBean<MallOrderListAdminVO> selectAuditedMallOrderList(MallOrderListAdminQuery query) {

        //家具分期订单ID列表
        List<Long> productIdsList = dictService.selectProductIdsListInCache();
        productIdsList = productIdsList.stream().filter(id -> !Constants.JYD_PRODUCTID.equals(id)).collect(Collectors.toList());
        query.setProductIdsList(productIdsList);

        int total = orderGoodsExtraInfoMapper.selectAuditedMallOrderListCount(query);
        List<MallOrderListAdminVO> list = new ArrayList<>();
        if(total > 0) {
            query.startPage();
            list = orderGoodsExtraInfoMapper.selectAuditedMallOrderList(query);
            list.stream().forEach(o -> {
                if(!CommonUtils.isEmpty(o.getYearRate())) {
                    o.setYearRateBd(new BigDecimal(o.getYearRate()).multiply(new BigDecimal(100)));
                    o.setYearRate(null);
                }
            });
        }
        return new PageBean<>(list, total);
    }

    @Override
    public PageBean<MallOrderListAdminVO> selectRejectMallOrderList(MallOrderListAdminQuery query) {

        //家具分期订单ID列表
        List<Long> productIdsList = dictService.selectProductIdsListInCache();
        productIdsList = productIdsList.stream().filter(id -> !Constants.JYD_PRODUCTID.equals(id)).collect(Collectors.toList());
        query.setProductIdsList(productIdsList);

        int total = orderGoodsExtraInfoMapper.selectRejectMallOrderListCount(query);
        List<MallOrderListAdminVO> list = new ArrayList<>();
        if(total > 0) {
            query.startPage();
            list = orderGoodsExtraInfoMapper.selectRejectMallOrderList(query);
            list.stream().forEach(o -> {
                if(!CommonUtils.isEmpty(o.getYearRate())) {
                    o.setYearRateBd(new BigDecimal(o.getYearRate()).multiply(new BigDecimal(100)));
                    o.setYearRate(null);
                }
            });
        }
        return new PageBean<>(list, total);
    }

    @Override
    public MallOrderDetailAdminVO selectMallOrderDetailAdminVO(Long orderId) {

        MallOrderDetailAdminVO modelVo = orderGoodsExtraInfoMapper.selectMallOrderDetailAdminVO(orderId);
        state(modelVo != null, "分期订单信息异常");

        //查询订单购买证明
        List<OrderImageListVO> purchaseProofList = orderImageMapper.selectOrderImageListByOrderId(orderId, OrderImageType.PURCHASE_PROOF);
        if(!CommonUtils.isEmpty(purchaseProofList)) {
            purchaseProofList.stream().forEach(i -> {
                i.setSrc(fileService.getFileUrl(i.getPath(), Constants.MALL_BUCKET_NAME));
            });
        }

        //设置值
        modelVo.setSexText(modelVo.getSex().getText());
        modelVo.setAge(CommonUtils.getAgeByIdNo(modelVo.getIdNo()));
        modelVo.setPurchaseProofList(purchaseProofList);

        return modelVo;
    }

    @Override
    @Transactional
    public void assignManager(Long orderId, Long managerId) {
        //验证管理员是否审核员角色
        Manager manager = new Manager();
        manager.setId(managerId);
        manager = managerMapper.selectOne(manager);
        state(manager != null, "审核员不存在");
        boolean flag = Constants.AUDIT_ROLE_ID.equals(manager.getRoleId());
        state(flag, "该管理员用户不是审核员");

        //先根据订单id，删除原有的分配信息
        OrderManager record = new OrderManager();
        record.setOrderId(orderId);
        orderManagerMapper.delete(record);
        //进行分配
        OrderManager orderUser = new OrderManager();
        orderUser.setOrderId(orderId);
        orderUser.setManagerId(managerId);
        orderUser.setCreateTime(new Date());
        orderManagerMapper.insertSelective(orderUser);
    }

    @Override
    @Transactional
    public void doAuditPurchaseProof(MallOrderAuditPurchaseProofAO auditAO, Long managerId) {

        //验证当前管理员是否审核员角色
        Manager manager = new Manager();
        manager.setId(managerId);
        manager = managerMapper.selectOne(manager);
        state(manager != null, "审核员不存在");
        boolean flag = Constants.AUDIT_ROLE_ID.equals(manager.getRoleId());
        state(flag, "当前管理员用户不是审核员，无审核权限！");

        state(!(!"PASS".equals(auditAO.getAuditResult()) && !"REJECT".equals(auditAO.getAuditResult())), "审核参数有误!");

        OrderGoodsExtraInfo dbOrderGoodsExtraInfo = new OrderGoodsExtraInfo();
        dbOrderGoodsExtraInfo.setOrderId(auditAO.getOrderId());
        dbOrderGoodsExtraInfo = orderGoodsExtraInfoMapper.selectOne(dbOrderGoodsExtraInfo);
        state(dbOrderGoodsExtraInfo != null, "分期订单信息异常");

        Date time = new Date();
        OrderGoodsExtraInfo updateOrderGoodsExtraInfo = new OrderGoodsExtraInfo();
        updateOrderGoodsExtraInfo.setId(dbOrderGoodsExtraInfo.getId());
        if("PASS".equals(auditAO.getAuditResult())) {
            //审核-通过
            updateOrderGoodsExtraInfo.setGoodsOrderStatus(GoodsOrderStatus.AUDIT_PASS);

        }else if("REJECT".equals(auditAO.getAuditResult())) {
            //审核-拒绝
            updateOrderGoodsExtraInfo.setGoodsOrderStatus(GoodsOrderStatus.AUDIT_REJECT);
            updateOrderGoodsExtraInfo.setBankmaAuditRejectReason(auditAO.getRejectReason());

        }
        //查找确定订单的最终状态 finalStatus
        OrderFinalStatusE finalStatus = mallOrderStatusService.getOrderFinalStatus(dbOrderGoodsExtraInfo.getThirdSource(), dbOrderGoodsExtraInfo.getProductId(), dbOrderGoodsExtraInfo.getThirdStatus(), updateOrderGoodsExtraInfo.getGoodsOrderStatus());
        state(finalStatus != null, "更新订单数据失败：订单状态判断异常。");
        updateOrderGoodsExtraInfo.setFinalStatus(finalStatus);
        updateOrderGoodsExtraInfo.setFinalStatusText(finalStatus.getText());
        updateOrderGoodsExtraInfo.setUpdateTime(time);
        orderGoodsExtraInfoMapper.updateByPrimaryKeySelective(updateOrderGoodsExtraInfo);
    }
}
